﻿using Common.Api.Client;
using Microsoft.AspNetCore.Components.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Components
{
    public partial class BootstrapInputFile
    {

        protected override void OnAfterRender(bool firstRender)
        {
            if(firstRender)
            {
                this.FileName = "文件下载";
                StateHasChanged();
            }
            base.OnAfterRender(firstRender);
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if(firstRender)
            {
                await LoadFileName();
            }
            await base.OnAfterRenderAsync(firstRender);
        }

        private async Task OnInputFileChange(InputFileChangeEventArgs e)
        {

            if (await Verification(e) == false)
            {
                await InvokeAsync(StateHasChanged);
                return;
            }

            var files = e.GetMultipleFiles(maximumFileCount: MaximumFileCount);

            if (await Verification(files) == false)
            {
                await InvokeAsync(StateHasChanged);
                return;
            }
            SetDisabled(true);

            var imageFile = files.FirstOrDefault();
            var operateResult = await CommonClientFactory.Download.AsyncUpload(imageFile.OpenReadStream(maxAllowedSize: MaxAllowedSize), imageFile.Name);
            if (operateResult.IsSuccess)
            {
                this.Value = operateResult.Data.FileId;
            }
            else
            {
                await this.Alert("上传失败!");
            }
            SetDisabled(false);
            await InvokeAsync(StateHasChanged);

        }

        /// <summary>
        /// 初始加载图片
        /// </summary>
        private async Task LoadFileName()
        {
            if (this.Value > 0)
            {
                await InvokeAsync(StateHasChanged);
                var operateResult = await CommonClientFactory.Download.GetDownloadById(this.Value);
                if (operateResult.IsSuccess)
                {
                    this.FileName = operateResult.Data.FileName;
                }
                await InvokeAsync(StateHasChanged);
            }
        }

        private void DownloadFile()
        {

        }
    }
}
